unit FBase;

interface
uses
	Windows, OpenGl, FOpenGL;

type
	TWindow = Record
		X : Integer;
		Y : Integer;
	end;
	Float = Single;

var
	rc : HGLRC;
	dc : HDC;
	Window : TWindow;

	SelectMode : boolean;
	glNameCount : GLUInt;

procedure InitGL(handle : Cardinal);
procedure glDraw();

implementation
uses
	FInterface, FFonts, FTerrain, FCursor, FView, FModel;

procedure InitGL(handle : Cardinal);
var
	pfd : TPixelFormatDescriptor;
	pf  : Integer;
begin
	InitOpenGL();
	dc := GetDC(handle);

	pfd.nSize := sizeof(pfd);
	pfd.nVersion := 1;
	pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER or 0;
	pfd.iPixelType := PFD_TYPE_RGBA;
	pfd.cColorBits := 32;

	pf := ChoosePixelFormat(dc, @pfd);

	SetPixelFormat(dc, pf, @pfd);
	rc := wglCreateContext(dc);
	wglMakeCurrent(dc,rc);

	glClearColor(1, 1, 1, 0);
	glClearDepth(1.0);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	glShadeModel(GL_SMOOTH);

	glCreateFont();
end;

procedure Draw();
begin
	glNameCount := 0;

	DrawTerrain(Terrain);
	if not SelectMode then
		DrawModel();
	DrawInterface();

	glLoadName(glNameCount);
end;

procedure GetPicking();
var
	selectBuff : Array[0..23] of glUint;
	viewport : Array[1..4] of glUint;
	hits : TGLint;
begin
	glGetIntegerv(GL_VIEWPORT, @viewport);
	glSelectBuffer(23, @selectBuff);

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glRenderMode(GL_SELECT);
	glInitNames();
	glPushName(0);
	glLoadIdentity();
	Mouse.Hover := -1;

	glMatrixMode(GL_PROJECTION);
	gluPickMatrix(Mouse.X, viewport[4] - Mouse.Y, 1, 1, @viewport);
	gluPerspective(80, Window.X / Window.Y, 0.0001, 3000);
	gluLookAt(View.camx, View.camy, View.camz, View.tarx, View.tary, View.tarz, 0, 1, 0);    //1650

	SelectMode := true;
	Draw();               
	SelectMode := false;

	hits := glRenderMode(GL_RENDER);
	if (hits > 0) then
		Mouse.Hover := selectBuff[3]
	else
		Mouse.Hover := -1;

	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
end;

procedure glDraw();
begin
	SelectMode := false;
	glDepthMask(true);
	glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);

	OnUpdateView();
	GetPicking();
	UpdateView();
	Draw();

	DisplayCursor();
	glFlush();
	SwapBuffers(dc);
end;
end.

